<?php


namespace App\Extensions\Grid\Displayers;


use Encore\Admin\Admin;
use Encore\Admin\Grid\Displayers\Modal;
use Encore\Admin\Grid\Simple;
use Illuminate\Contracts\Support\Renderable;

class FileModal extends Modal
{

    protected function getLoadUrl()
    {
        $renderable = str_replace('\\', '_', $this->renderable);

        return admin_route('handle-renderable', compact('renderable'));
    }

    /**
     * @param \Closure|string $callback
     *
     * @return mixed|string
     */
    public function display($callback = null)
    {
        $query = [];
        if (func_num_args() == 3) {
            list($title, $callback, $query) = func_get_args();
        } elseif (func_num_args() == 2) {
            list($title, $callback) = func_get_args();
        } elseif (func_num_args() == 1) {
            $title = $this->trans('title');
        } else {
            $title = '详情';
        }
        $query['token'] = method_exists($this->row, 'token') ? $this->row->token() : 'token';

        $html = '';

        if ($async = is_subclass_of($callback, Renderable::class)) {
            $this->renderable = $callback;
        } else {
            $html = call_user_func_array($callback->bindTo($this->row), [$this->row]);
        }

        $name = $this->getKey() . '-' . str_replace('.', '_', $this->getColumn()->getName());

        \Encore\Admin\Facades\Admin::script($this->deleteScript($name));
        return Admin::component('admin::components.column-modal', [
            'url' => $this->getLoadUrl() . '&' . http_build_query($query),
            'async' => $async,
            'grid' => is_subclass_of($callback, Simple::class),
            'title' => $title,
            'html' => $html,
            'key' => $this->getKey(),
            'value' => $this->getValueHtml($this->value, $name),
            'name' => $name,
        ]);
    }

    protected function getValueHtml($value, $name)
    {
        if (is_array($value)) {
            $value = count($value);
        }
        if ($value) {
            return sprintf('<i class="fa fa-paperclip"></i><span id="grid-modal-%s-total">%s</span>', $name, $value);
        }
        return '';
    }

    protected function deleteScript($name)
    {

        return <<<SCRIPT
 $('#grid-modal-{$name}').on('click', '.modal-row-delete', function () {
            let obj = $(this);
            let id = obj.data('id');
            let href = obj.data('href');
            swal({
                title: "确认删除?",
                type: "warning",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "确认",
                showLoaderOnConfirm: true,
                cancelButtonText: "取消",
                preConfirm: function () {
                    return new Promise(function (resolve) {
                        $.ajax({
                            method: 'post',
                            url: href,
                            data: {
                                _method: 'delete',
                                _token: LA.token,
                            },
                            success: function (data) {
                                resolve(data);
                            }
                        });
                    });
                }
            }).then(function (result) {
                var data = result.value;
                if (typeof data === 'object') {
                    if (data.status) {
                        obj.parents('tr:first').remove()
                        $('#grid-modal-{$name}-total').html($('#grid-modal-{$name}').find('tbody>tr').length);
                        swal(data.message, '', 'success');
                    } else {
                        swal(data.message, '', 'error');
                    }
                }
            });
        });
SCRIPT;

    }
}
